'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');
const OSS = require('ali-oss');
const random = require('string-random');
// const moduleegg = require("egg");


const aliInfo = {
  region: 'oss-cn-beijing',
  bucket: 'bucket-yufei',
  accessKeyId: 'LTAI5t6zrh5qyTT3jBfgQzvM',
  accessKeySecret: 'gSPmVBMtrFc0U4iv4B7NNihnbYjZJo',
  endpoint: 'oss-cn-beijing.aliyuncs.com',
};
const client = new OSS(aliInfo);

class AliOssController extends Controller {
  async upload() {
    const { ctx } = this;
    const file = ctx.request.files[0];// 获取前端传来的文件
    let result;
    let img;
    const index = ctx.header.index;
    try {
      result = await client.put(`picture/${random(8) + file.filename}`, file.filepath); // 上传文件到oss,第一个参数为文件存放地址+文件名，第二个是文件路径 详细见（https://help.aliyun.com/document_detail/111265.html?spm=a2c4g.11186623.6.1382.29157916dwptKL）
      img = await ctx.model.Picture.create({ // 将oss返回的图片服务器地址存到视频表中
        imgUrl: result.url,
      });
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    ctx.body = {
      result,
      img,
      index,
      state: 'success',
      msg: '新增成功',
    };
  }
  // 上传视频，参数与上相同
  async uploadVideo() {
    const { ctx } = this;
    const file = ctx.request.files[0];
    console.log(file);
    let result;
    let video;
    try {
      // 处理文件，比如上传到云端
      result = await client.put(`video/${random(8) + file.filename}`, file.filepath);
      video = await ctx.model.Video.create({
        videoUrl: result.url,
      });
    } finally {
      // 需要删除临时文件
      await fs.unlink(file.filepath);
    }
    ctx.body = {
      result,
      video,
      state: 'success',
      msg: '新增成功',
    };
  }
  // 上传多个图片
  async uploadImages() {
    const { ctx } = this;
    console.log(ctx.request.body);
    console.log('got %d files', ctx.request.files.length);
    let result;// 保存结果
    let img; // 保存路径
    try {
      // 遍历处理多个文件
      for (const file of ctx.request.files) {
        console.log('tmp filepath: ' + file.filepath);
        // 处理文件，比如上传到云端
        result = await client.put(`picture/${random(8) + file.filename}`, file.filepath);
        img = result.filepath;
      }
    } finally {
      // 需要删除临时文件
      await ctx.cleanupRequestFiles();
    }
    ctx.body = {
      result,
      img,
      state: 'success',
      msg: '新增成功',
    };
  }
}

module.exports = AliOssController;

